#!/usr/bin/env python
#vhost autocheck date 20210824
import os
import time
import sys
import hashlib
import sqlite3
import subprocess
import urllib2

def md5hex(FilePath):
    if os.path.exists(FilePath):
        with open(FilePath,'rb') as f:
            md5obj = hashlib.md5()
            md5obj.update(f.read())
            md5value = md5obj.hexdigest()
            return md5value
    else:
        return value

def get_id():
    url =  'http://databackup.cndns.com/backup-report/report_id.php'
    conn = urllib2.urlopen(url,timeout=10)
    str=conn.read()
    tmp = str.split("=")

    if tmp[1].strip() != '':
        id = tmp[1].strip()
    else:
        exit()

    fn = open('/root/Autocheck/id.cfg','w')
    fn.write(str)
    fn.close()
    conn.close()



def write_log(logs):
    f = open(log_path, 'a')
    f.write("[" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "] ")
    f.write(logs)
    f.write("\n")
    f.close

if __name__ == "__main__":

    security_code='CKVHOST2015'
    id_cfg = '/root/Autocheck/id.cfg'
    log_path = os.path.split(os.path.realpath(__file__))[0] + "/check.log"
    #GET id
    if not os.path.exists(id_cfg):
        get_id()

    fn = open(id_cfg,'r')
    for line in fn:
        if 'server_id' in line:
            tmp = line.split("=")
            if tmp[1].strip() != 'NULL' and tmp[1].strip() != '':
                svr_id = tmp[1].strip()
            else:
                os.remove(id_cfg)
                exit()
    fn.close()



    check_list = {'cron':'/var/spool/cron/root','ssh':'/etc/ssh/sshd_config','iptables':'/root/Autocheck/iptables.tmp','httpd.conf':'/etc/httpd/conf/httpd.conf','my.cnf':'/etc/my.cnf'}#
    db_path="/root/Autocheck/md5.db"

    if( len(sys.argv) == 2):
        conn = sqlite3.connect(db_path)
        c = conn.cursor()
        if(sys.argv[1] == "init"):
            get_id()
            del_table='DROP TABLE IF EXISTS md5_list'
            c.execute(del_table)
            create_table='CREATE TABLE IF NOT EXISTS md5_list (NAME TEXT PRIMARY KEY NOT NULL,MD5 TEXT NOT NULL);'
            c.execute(create_table)

            #iptables
            os.system('/sbin/iptables -L -n|/bin/grep -v -E "REJECT|RETURN|^DROP|^f2b-|^IN_HIDS_|:444"  >/root/Autocheck/iptables.tmp')

            for key,value in check_list.items():
                name = key
                fmd5= md5hex(value)
                sql="INSERT INTO md5_list VALUES ('%s','%s')" % (name,fmd5)
                c.execute(sql)

            conn.commit()





        if(sys.argv[1] == "check"):
            #security code
            f_md5=md5hex(db_path)
            code=f_md5+security_code
            m1 = hashlib.md5()
            m1.update(code)
            svr_token = m1.hexdigest()

            #check
            bad_service=''
            for key,value in check_list.items():

                if( key == 'iptables' ):
                    os.system('/sbin/iptables -L -n|/bin/grep -v -E "REJECT|RETURN|^DROP|^f2b-|^IN_HIDS_|:444" >/root/Autocheck/iptables.tmp')

                sql="SELECT * FROM md5_list where NAME='"+key+"'"

                cursor = c.execute(sql)
                for row in cursor:
                    fmd5= md5hex(value)
                    if(fmd5 == row[1]):
                        print key + " sql:" + row[1] + " check:" + fmd5 +"  OK"
                    else:
                        print key + " sql:" + row[1] + " check:" + fmd5+"  CHANGED"
                        if( bad_service == ''):
                            bad_service = key
                        else:
                            bad_service = key + "|" + bad_service

            #report to server
            url = 'http://databackup.cndns.com/auto_ck/check_api.php?type=vhost&token=%s&svr_id=%s&f_md5=%s&bad_service=%s' % (svr_token,svr_id,f_md5,bad_service)
            attempts = 0
            success = False
            while attempts < 5 and not success:
                try:
                    rep_conn = urllib2.Request(url)
                    p = urllib2.urlopen(rep_conn,timeout=60)
                    print url
                    print 'report ok'
                    success = True
                    write_log("successfull")
                except Exception,e:
                    attempts += 1
                    time.sleep(60)
                    write_log("failed")
                    if attempts == 5:
                        print e,url
                        print 'ERROR: job report error'
            p.close()

        #close sqlite connection
        conn.close()
